import { ChangeDetectorRef, Component, Injector, Input, OnInit } from '@angular/core';
import { ControlWidget, SFComponent, SFItemComponent } from '@delon/form';
import { DictService } from '@shared';
import { _HttpClient } from '@delon/theme';

@Component({
  selector: 'sf-dict-select',
  template: `
    <sf-item-wrap
      [id]="id"
      [schema]="schema"
      [ui]="ui"
      [showError]="showError"
      [error]="error"
      [showTitle]="schema.title"
    >
      <nz-select style="width: 100%;" nzPlaceHolder="请选择"  nzShowSearch nzAllowClear nz_input  [ngModel]="value" (ngModelChange)="change($event)">
        <nz-option *ngFor="let dict of dictList" [nzValue]="dict.value" [nzLabel]="dict.label"></nz-option>
      </nz-select>
    </sf-item-wrap>
  `,
})
export class DictSelectWidget extends ControlWidget implements OnInit {
  static readonly KEY = 'dict-select';
  config: {};
  dictCode: string;
  dictList;
  constructor(private dictService: DictService,cd: ChangeDetectorRef, injector: Injector) {
    super(cd,injector,null,null)
  }

  ngOnInit(): void {
    this.dictCode=this.ui.dictCode;
    this.getDict();
  }

  change(value: string) {
    if (this.ui.change) this.ui.change(value);
    this.setValue(value);
  }
  getDict() {
    const dict = this.dictCode.split(',');
    if (dict.length === 1) {
      this.dictService.getDict(dict[0]).subscribe((res) => (this.dictList = res));
    } else if (dict.length === 3) {
      this.dictService.getDictByTable(dict[0], dict[1], dict[2]).subscribe((res) => (this.dictList = res));
    }
  }
}
